package com.yuqing.sentimentapp.yqlist;

import android.content.Context;
import android.text.TextUtils;

import com.linkface.baselibrary.utils.LogUtil;
import com.linkface.baselibrary.utils.ThreadManager;
import com.yuqing.sentimentapp.base.BaseActivity;
import com.yuqing.sentimentapp.event.CommonEvent;
import com.yuqing.sentimentapp.event.IssuedEvent;
import com.yuqing.sentimentapp.home.bean.DeptBean;
import com.yuqing.sentimentapp.home.bean.IssuedPrepareDataBean;
import com.yuqing.sentimentapp.home.bean.IssuedSaveRegionDataBean;
import com.yuqing.sentimentapp.home.bean.RegionBean;
import com.yuqing.sentimentapp.home.presenter.IssuedPresenter;
import com.yuqing.sentimentapp.home.presenter.impl.IssuedPresenterImpl;
import com.yuqing.sentimentapp.home.view.IssuedView;
import com.yuqing.sentimentapp.login.bean.LoginResultBean;
import com.yuqing.sentimentapp.utils.SharePrefrenceHelper;
import com.yuqing.sentimentapp.utils.ToastUtil;
import com.yuqing.sentimentapp.widget.jdaddressselector.BottomDialog;
import com.yuqing.sentimentapp.widget.jdaddressselector.DataProvider;
import com.yuqing.sentimentapp.widget.jdaddressselector.ISelectAble;
import com.yuqing.sentimentapp.widget.jdaddressselector.SelectedListener;
import com.yuqing.sentimentapp.widget.jdaddressselector.Selector;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by shenhe on 2019/4/29.
 */
public class IssuedHelper implements IssuedView<IssuedPrepareDataBean> {

    private Context mContext;
    private IssuedPresenter mPresenter;
    private static IssuedHelper issuedHelper;
    private BottomDialog dialog;

    private IssuedHelper(Context context) {
        this.mContext = context;
        mPresenter = new IssuedPresenterImpl(context, this);
    }

    public static IssuedHelper getInstance(Context context) {
        //不能用单利
//        if (issuedHelper == null) {
//            synchronized (IssuedHelper.class) {
//                if (issuedHelper == null) {
//                    issuedHelper = new IssuedHelper(context);
//                }
//            }
//        }
        issuedHelper = new IssuedHelper(context);
        return issuedHelper;
    }

    public IssuedPresenter getIssuedPresenter() {
        return mPresenter;
    }

    @Override
    public void returnIssuedPrepareSuccess(IssuedPrepareDataBean result, String articleId, int position) {
        if (result == null) {
            ToastUtil.showShort("下发成功");
            EventBus.getDefault().post(new IssuedEvent(position, "", ""));
            return;
        }
        IssuedPrepareDataBean.DataBean data = result.getData();
        if (data == null) {
            ToastUtil.showShort("下发成功");
            EventBus.getDefault().post(new IssuedEvent(position, "", ""));
            return;
        }
        IssuedPrepareDataBean.DataBean.ResultBean regionBean = data.getResult();
        if (regionBean == null) {
            ToastUtil.showShort("下发成功");
            EventBus.getDefault().post(new IssuedEvent(position, data.getSubStatus(), data.getPubId()));
            return;
        }
        switch (data.getCode()) {
            default://舆情地区未设置
            case 1://舆情地区未设置, 并返回地区数据
                showRegionDialog(articleId, regionBean, position);
                break;
            case 2://本地区下没有设置部门
                //直接下发

            case 3://本地区下设置了多个部门
                List<DeptBean> dept = regionBean.getDept();
                if (dept == null || dept.size() <= 1) {
                    return;
                }
                showDeptDialog(dept, articleId, position);
                break;
        }
    }

    private void showDeptDialog(List<DeptBean> dept, String articleId, int position) {
        ((BaseActivity) mContext).startProgressDialog();
        ThreadManager.getThreadPollProxy().execute(() -> {
            Selector selector = new Selector(mContext, 1);
            selector.setDataProvider(new DataProvider() {
                @Override
                public void provideData(int currentDeep, String preId, DataReceiver receiver) {
                    //根据tab的深度和前一项选择的id，获取下一级菜单项
                    LogUtil.i("provideData: currentDeep >>> " + currentDeep + " preId >>> " + preId);
                    receiver.send(getDeptDatas(dept, currentDeep, preId), "", "", "");
                }
            });
            selector.setTitle("选择部门");
            selector.setSelectedListener(new SelectedListener() {
                @Override
                public void onAddressSelected(ArrayList<ISelectAble> selectAbles) {
                    if (selectAbles.get(0) == null) {
                        ToastUtil.showShort("请选择一个部门");
                        return;
                    }
                    //再调用预下发
                    mPresenter.loadIssuedPrepareRequest(articleId, selectAbles.get(0).getId() + "", position);
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                }
            });

            selector.setCloseListener(() -> {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            });

            ((BaseActivity) mContext).runOnUiThread(() -> {
                ((BaseActivity) mContext).stopProgressDialog();
                dialog = new BottomDialog(mContext);
                dialog.setCanceledOnTouchOutside(false);
                dialog.init(mContext, selector);
                dialog.show();
            });
        });
    }

    private List<ISelectAble> getDeptDatas(List<DeptBean> dept, int currentDeep, String preId) {
        List<ISelectAble> data = new ArrayList<>();
        if (dept == null || dept.size() <= 0) return data;
        for (int i = 0; i < dept.size(); i++) {
            final int finalJ = i;
            data.add(new ISelectAble() {
                @Override
                public String getName() {
                    return dept.get(finalJ).getDeptName();
                }

                @Override
                public String getId() {
                    return dept.get(finalJ).getDeptCode();
                }

                @Override
                public Object getArg() {
                    return this;
                }
            });
        }
        return data;
    }

    @Override
    public void returnSaveRegionResultSuccess(IssuedSaveRegionDataBean result, String articleId, int position) {
        //保存地区成功，并返回部门信息
        //如果只有一个部门，则直接下发（服务器处理）
        //否则显示部门弹窗
        if (result == null) {
            ToastUtil.showShort("下发成功");
            EventBus.getDefault().post(new IssuedEvent(position,  "", ""));
            return;
        }
        IssuedSaveRegionDataBean.DataBean data = result.getData();
        if (data == null) {
            ToastUtil.showShort("下发成功");
            EventBus.getDefault().post(new IssuedEvent(position,  "", ""));
            return;
        }
        IssuedSaveRegionDataBean.DataBean.ResultBean deptResult = data.getResults();
        if (deptResult == null) {
            ToastUtil.showShort("下发成功");
            EventBus.getDefault().post(new IssuedEvent(position, data.getSubStatus(), data.getPubId()));
            return;
        }
        List<DeptBean> dept = deptResult.getSubDepts();
        if (dept == null || dept.size() <= 1) {
            ToastUtil.showShort("下发成功");
            EventBus.getDefault().post(new CommonEvent(position, data.getSubStatus(), data.getPubId()));
            return;
        }
        showDeptDialog(dept, articleId, position);
    }

    private ArrayList<ISelectAble> getRegionDatas(IssuedPrepareDataBean.DataBean.ResultBean regionBean, int currentDeep, String preId) {
        ArrayList<ISelectAble> data = new ArrayList<>();
        if (currentDeep == 0) {//省
            List<RegionBean> province = regionBean.getProvince();
            if (province == null) return data;
            LoginResultBean.DataBean.UserBean user = SharePrefrenceHelper.getUser();
            if (user != null && user.getDeptVo() != null) {
                //总队身份不能修改省
                //总队身份,并且省不为空，第一深度只返回选中省的数据（只有一条），达到不能修改省的目的
                String deptLevel = user.getDeptVo().getDeptLevel();
                if (!TextUtils.isEmpty(deptLevel) && TextUtils.equals(deptLevel, "1")) {
                    if (!TextUtils.isEmpty(regionBean.getProvinceCode())) {
                        for (int i = 0; i < province.size(); i++) {
                            if (TextUtils.equals(regionBean.getProvinceCode(), province.get(i).getCode())) {
                                int finalI = i;
                                data.add(new ISelectAble() {
                                    @Override
                                    public String getName() {
                                        return province.get(finalI).getName();
                                    }

                                    @Override
                                    public String getId() {
                                        return province.get(finalI).getCode();
                                    }

                                    @Override
                                    public Object getArg() {
                                        return this;
                                    }
                                });
                                break;
                            }
                        }
                        return data;
                    }
                }
            }
            //不是总队身份，返回全部省数据
            for (int j = 0; j < province.size(); j++) {
                final int finalJ = j;
                data.add(new ISelectAble() {
                    @Override
                    public String getName() {
                        return province.get(finalJ).getName();
                    }

                    @Override
                    public String getId() {
                        return province.get(finalJ).getCode();
                    }

                    @Override
                    public Object getArg() {
                        return this;
                    }
                });
            }
            return data;
        }
        if (currentDeep == 1) {//市
            List<RegionBean> city = regionBean.getCity();
            if (city == null) return data;
            for (int j = 0; j < city.size(); j++) {
                if (TextUtils.equals(preId, city.get(j).getParentCode())) {//比较省的编码
                    final int finalJ = j;
                    data.add(new ISelectAble() {
                        @Override
                        public String getName() {
                            return city.get(finalJ).getName();
                        }

                        @Override
                        public String getId() {
                            return city.get(finalJ).getCode();
                        }
                        @Override
                        public Object getArg() {
                            return this;
                        }
                    });
                }
            }
            return data;
        }
        if (currentDeep == 2) {//县
            List<RegionBean> county = regionBean.getCounty();
            if (county == null) return data;
            for (int j = 0; j < county.size(); j++) {
                if (TextUtils.equals(preId, county.get(j).getParentCode())) {//比较市的编码
                    final int finalJ = j;
                    data.add(new ISelectAble() {
                        @Override
                        public String getName() {
                            return county.get(finalJ).getName();
                        }

                        @Override
                        public String getId() {
                            return county.get(finalJ).getCode();
                        }

                        @Override
                        public Object getArg() {
                            return this;
                        }
                    });
                }
            }
            return data;
        }

        return data;
    }

    private void showRegionDialog(String articleId, IssuedPrepareDataBean.DataBean.ResultBean regionBean, int position) {
        ((BaseActivity) mContext).startProgressDialog();
        ThreadManager.getThreadPollProxy().execute(() -> {
            Selector selector = new Selector(mContext, 3);
            selector.setDataProvider(new DataProvider() {
                @Override
                public void provideData(int currentDeep, String preId, DataReceiver receiver) {
                    //根据tab的深度和前一项选择的id，获取下一级菜单项
                    LogUtil.i("provideData: currentDeep >>> " + currentDeep + " preId >>> " + preId);
                    receiver.send(getRegionDatas(regionBean, currentDeep, preId), regionBean.getProvinceCode(), regionBean.getCityCode(), regionBean.getCountyCode());
                }
            });
            selector.setTitle("选择地区");
            selector.setSelectedListener(new SelectedListener() {
                @Override
                public void onAddressSelected(ArrayList<ISelectAble> selectAbles) {
                    if (selectAbles.get(0) == null && selectAbles.get(1) == null && selectAbles.get(2) == null) {
                        ToastUtil.showShort("请选择一个地区");
                        return;
                    }
                    mPresenter.saveIssuedRegionRequest(articleId, selectAbles.get(0) == null ? "" : selectAbles.get(0).getId(),
                            selectAbles.get(1) == null ? "" : selectAbles.get(1).getId(),
                            selectAbles.get(2) == null ? "" : selectAbles.get(2).getId(), position);
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                }
            });

            selector.setCloseListener(() -> {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            });

            ((BaseActivity) mContext).runOnUiThread(() -> {
                ((BaseActivity) mContext).stopProgressDialog();
                dialog = new BottomDialog(mContext);
                dialog.init(mContext, selector);
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
            });
        });
    }

    @Override
    public void onSuccess(IssuedPrepareDataBean data) {

    }

    @Override
    public void onFailure(String message) {
        ToastUtil.showShort(message);
    }

    public void onDestroy() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        dialog = null;

        if (mContext != null) {
            mContext = null;
        }
    }
}
